"""角色模板库和技能模板库演示"""

import sys
import os
import uuid
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from models.character_template import CharacterTemplateLibrary, CharacterClass
from models.skill_template import SkillTemplateLibrary, SkillCategory
from models.character import CharacterType
from game.game_manager import GameManager
import json

def create_template_based_battle():
    """使用模板库创建战斗"""
    print("=== 使用模板库创建战斗 ===")
    
    # 创建玩家队伍
    print("\n创建玩家队伍...")
    player_characters = []
    
    # 创建战士
    warrior = CharacterTemplateLibrary.create_character_from_template(
        "warrior_basic", f"player_warrior_{uuid.uuid4().hex[:8]}", CharacterType.PLAYER, level=5
    )
    player_characters.append(warrior)
    print(f"创建战士: {warrior.name} (等级5)")
    print(f"  属性: HP={warrior.max_hp}, ATK={warrior.attack}, DEF={warrior.defense}, SPD={warrior.speed}")
    
    # 创建法师
    mage = CharacterTemplateLibrary.create_character_from_template(
        "mage_elemental", f"player_mage_{uuid.uuid4().hex[:8]}", CharacterType.PLAYER, level=4
    )
    player_characters.append(mage)
    print(f"创建法师: {mage.name} (等级4)")
    print(f"  属性: HP={mage.max_hp}, ATK={mage.attack}, DEF={mage.defense}, SPD={mage.speed}")
    
    # 创建治疗师
    healer = CharacterTemplateLibrary.create_character_from_template(
        "healer_priest", f"player_healer_{uuid.uuid4().hex[:8]}", CharacterType.PLAYER, level=4
    )
    player_characters.append(healer)
    print(f"创建治疗师: {healer.name} (等级4)")
    print(f"  属性: HP={healer.max_hp}, ATK={healer.attack}, DEF={healer.defense}, SPD={healer.speed}")
    
    # 创建敌方队伍
    print("\n创建敌方队伍...")
    enemy_characters = []
    
    # 创建狂战士
    berserker = CharacterTemplateLibrary.create_character_from_template(
        "berserker_fury", f"enemy_berserker_{uuid.uuid4().hex[:8]}", CharacterType.ENEMY, level=5
    )
    enemy_characters.append(berserker)
    print(f"创建狂战士: {berserker.name} (等级5)")
    print(f"  属性: HP={berserker.max_hp}, ATK={berserker.attack}, DEF={berserker.defense}, SPD={berserker.speed}")
    
    # 创建死灵法师
    necromancer = CharacterTemplateLibrary.create_character_from_template(
        "necromancer_dark", f"enemy_necromancer_{uuid.uuid4().hex[:8]}", CharacterType.ENEMY, level=4
    )
    enemy_characters.append(necromancer)
    print(f"创建死灵法师: {necromancer.name} (等级4)")
    print(f"  属性: HP={necromancer.max_hp}, ATK={necromancer.attack}, DEF={necromancer.defense}, SPD={necromancer.speed}")
    
    return player_characters, enemy_characters

def show_skill_library():
    """展示技能库"""
    print("\n\n=== 技能库展示 ===")
    
    # 按分类展示技能
    categories = [SkillCategory.DAMAGE, SkillCategory.HEAL, SkillCategory.BUFF, SkillCategory.CONTROL]
    
    for category in categories:
        skills = SkillTemplateLibrary.get_templates_by_category(category)
        print(f"\n{category.value.upper()} 技能 ({len(skills)}个):")
        
        for skill in skills[:5]:  # 只显示前5个
            print(f"  {skill.name}:")
            print(f"    描述: {skill.description}")
            print(f"    范围: {skill.range_size} | 距离: {skill.max_distance}")
            print(f"    数值: {skill.base_value} + {skill.percentage_value}% 攻击力")
            print(f"    冷却: {skill.cooldown} 回合")
            if skill.effects:
                print(f"    特效: {skill.effects[0]['type'] if skill.effects else '无'}")
            print(f"    标签: {', '.join(skill.tags)}")
            print()

def show_character_library():
    """展示角色库"""
    print("\n\n=== 角色库展示 ===")
    
    # 按职业展示角色
    classes = [CharacterClass.WARRIOR, CharacterClass.MAGE, CharacterClass.HEALER, CharacterClass.ASSASSIN]
    
    for char_class in classes:
        templates = CharacterTemplateLibrary.get_templates_by_class(char_class)
        print(f"\n{char_class.value.upper()} 职业 ({len(templates)}个):")
        
        for template in templates:
            print(f"  {template.name}:")
            print(f"    描述: {template.description}")
            print(f"    基础属性: HP={template.base_hp}, ATK={template.base_attack}, DEF={template.base_defense}, SPD={template.base_speed}")
            print(f"    战斗属性: 命中={template.base_hit_rate}%, 闪避={template.base_dodge_rate}%, 暴击={template.base_crit_rate}%, 暴击伤害={template.base_crit_damage}%")
            print(f"    成长: HP+{template.hp_growth}, ATK+{template.attack_growth}, DEF+{template.defense_growth}, SPD+{template.speed_growth}")
            print(f"    默认技能: {', '.join(template.default_skills)}")
            print(f"    标签: {', '.join(template.tags)}")
            print()

def create_custom_character():
    """创建自定义角色演示"""
    print("\n\n=== 自定义角色创建演示 ===")
    
    # 展示不同等级的同一角色
    template_id = "mage_elemental"
    levels = [1, 5, 10]
    
    print(f"展示 {template_id} 在不同等级的属性:")
    
    for level in levels:
        char = CharacterTemplateLibrary.create_character_from_template(
            template_id, f"mage_lv{level}", CharacterType.PLAYER, level=level
        )
        
        print(f"\n等级 {level}:")
        print(f"  HP: {char.max_hp}")
        print(f"  攻击: {char.attack}")
        print(f"  防御: {char.defense}")
        print(f"  速度: {char.speed}")
        print(f"  命中率: {char.hit_rate}%")
        print(f"  闪避率: {char.dodge_rate}%")
        print(f"  暴击率: {char.crit_rate}%")
        print(f"  暴击伤害: {char.crit_damage}%")

def skill_damage_comparison():
    """技能伤害对比"""
    print("\n\n=== 技能伤害对比 ===")
    
    # 创建不同攻击力的角色
    attack_values = [30, 50, 80]
    skill_ids = ["basic_attack", "power_strike", "fireball", "lightning_bolt"]
    
    print("技能伤害对比表 (不同攻击力):")
    print(f"{'技能名称':<12} {'描述':<20} {' | '.join([f'ATK={atk}' for atk in attack_values])}")
    print("-" * 80)
    
    for skill_id in skill_ids:
        try:
            template = SkillTemplateLibrary.get_template(skill_id)
            damages = [template.calculate_damage(atk) for atk in attack_values]
            damage_str = ' | '.join([f'{dmg:>6}' for dmg in damages])
            print(f"{template.name:<12} {template.description[:18]:<20} {damage_str}")
        except ValueError:
            print(f"{skill_id:<12} {'模板不存在':<20}")

def export_templates_to_json():
    """导出模板到JSON文件"""
    print("\n\n=== 导出模板数据 ===")
    
    # 导出角色模板
    character_templates = {}
    for template_id, template in CharacterTemplateLibrary.get_all_templates().items():
        character_templates[template_id] = template.to_dict()
    
    with open("character_templates.json", "w", encoding="utf-8") as f:
        json.dump(character_templates, f, ensure_ascii=False, indent=2)
    
    print(f"角色模板已导出到 character_templates.json ({len(character_templates)} 个模板)")
    
    # 导出技能模板
    skill_templates = {}
    for template_id, template in SkillTemplateLibrary.get_all_templates().items():
        skill_templates[template_id] = template.to_dict()
    
    with open("skill_templates.json", "w", encoding="utf-8") as f:
        json.dump(skill_templates, f, ensure_ascii=False, indent=2)
    
    print(f"技能模板已导出到 skill_templates.json ({len(skill_templates)} 个模板)")

def main():
    """主函数"""
    print("角色模板库和技能模板库演示")
    print("=" * 60)
    
    try:
        # 展示库内容
        show_character_library()
        show_skill_library()
        
        # 创建角色演示
        create_custom_character()
        
        # 技能对比
        skill_damage_comparison()
        
        # 创建战斗
        player_chars, enemy_chars = create_template_based_battle()
        
        # 导出数据
        export_templates_to_json()
        
        print("\n\n=== 演示完成 ===")
        print("模板库系统功能完整，可以用于快速创建角色和技能！")
        
    except Exception as e:
        print(f"\n演示过程中出现错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()